//
//  HSLiveDetailVC.m
//  HolyShit
//
//  Created by Robin on 2017/3/30.
//  Copyright © 2017年 HolyShit. All rights reserved.
//

#import "HSLiveDetailVC.h"
#import "HSLiveDataModel.h"
#import "HSLiveDetailCell.h"

@interface HSLiveDetailVC ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) HSLiveModel *model;

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIImageView *leftIcon;
@property (nonatomic, strong) UIImageView *rightIcon;
@property (nonatomic, strong) UILabel *leftName;
@property (nonatomic, strong) UILabel *rightName;
@property (nonatomic, strong) UILabel *leftScore;
@property (nonatomic, strong) UILabel *rightScore;
@property (nonatomic, strong) UILabel*timeLb;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSUInteger detail_ver;
@property (nonatomic, assign) NSUInteger live_ver;

@property (nonatomic, strong) NSMutableArray<HSLiveDataModel *> *liveData;
@property (nonatomic, strong) UILabel *failLb;

@end

@implementation HSLiveDetailVC

- (instancetype)initWithModel:(HSLiveModel *)model
{
    if (self = [super init]) {
        _model = model;
    }
    return self;
}

- (void)dealloc
{
    if (_timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.model.league.name_cn;
    [self.view addSubview:self.topView];
    [self.view addSubview:self.tableView];
    [self.hintView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topView.bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
//    [self.view addSubview:self.failLb];
    self.hintView.hintState = MYHintStateLoading;
    self.liveData  = @[].mutableCopy;
    [self updateTop];
    [self checkLiveData];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(refresh) userInfo:nil repeats:YES];
}

- (void)refresh
{
    if (self.tableView.isRefreshing) {
        return;
    }
    [self refreshTop];
    [self checkLiveData];
}

- (void)refreshTop
{
    if (self.detail_ver == 0) {
        return;
    }
    NSString *url = [NSString stringWithFormat:@"http://sportslive.firstblod.com/json/%@/%@_code.htm", self.model.sdate, self.model.id];
    @weakify(self);
    [[MYHttpHelper shareHelper] getWithUrl:url params:nil success:^(NSDictionary *dict) {
        @strongify(self);
//        [self.tableView endRefreshAndLoadMore];
        int v = [dict[@"code"] intValue];
        if (v > self.detail_ver) {
            [self updateTop];
        }
    } failed:^(NSError *error) {
        @strongify(self);
//        [self.tableView endRefreshAndLoadMore];
    }];
}

- (void)updateTop
{
    NSString *url = [NSString stringWithFormat:@"http://sportslive.firstblod.com/json/%@/%@.htm?%d", self.model.sdate, self.model.id, rand()];
    @weakify(self);
    [[MYHttpHelper shareHelper] getWithUrl:url params:nil success:^(NSDictionary *dict) {
        @strongify(self);
        NSString * hs = dict[@"home_score"];
        NSString *vs = dict[@"visit_score"];
        if (hs == nil || ![hs isKindOfClass:NSClassFromString(@"NSString")] || hs.length == 0) hs = @"0";
        if (vs == nil || ![vs isKindOfClass:NSClassFromString(@"NSString")] || vs.length == 0) vs = @"0";
        self.leftScore.text = hs;
        self.rightScore.text = vs;
        self.timeLb.text = dict[@"period_cn"];
        self.detail_ver = [dict[@"code"] intValue];
    } failed:^(NSError *error) {
        @strongify(self);
//        [self.tableView endRefreshAndLoadMore];
    }];
}

- (void)updateLiveDataUrl: (NSString *)url {
    @weakify(self);
    [[MYHttpHelper shareHelper] getWithUrl:url params:nil success:^(NSDictionary *dict) {
        @strongify(self);
        NSArray *ld_arr = dict[@"responseText"];
        NSUInteger cur_ver = self.live_ver;
        bool history = ld_arr.count > 2;
        int max_ver = 0;
        for (NSDictionary *obj in ld_arr) {
            int v = [obj[@"live_sid"] intValue];
            if (v > cur_ver || history)
            {
                HSLiveDataModel *ld = [[HSLiveDataModel alloc] init];
                ld.live_sid = v;
                ld.live_text = obj[@"live_text"];
                ld.live_ptime = obj[@"live_ptime"];
                ld.user_chn = obj[@"user_chn"];
                if (ld.live_ptime == nil
                    || ![ld.live_ptime isKindOfClass:NSClassFromString(@"NSString")]
                    || ld.live_ptime.length == 0) {
                    ld.live_ptime = [obj[@"live_time"] substringWithRange:NSMakeRange(11, 5)];
                }
                ld.img_url = obj[@"img_url"];
                if (ld.img_url == nil
                    || ![ld.img_url isKindOfClass:NSClassFromString(@"NSString")]
                    || ld.img_url.length == 0) {
                    ld.img_url = nil;
                }
                ld.text_color = [self readColor:obj[@"text_color"]];
                [self.liveData addObject:ld];
            }
            if (v > max_ver) max_ver = v;
        }
        if (max_ver > cur_ver || history) {
            if (max_ver > cur_ver) self.live_ver = max_ver;
            [self.liveData sortUsingComparator:^(HSLiveDataModel *v1, HSLiveDataModel *v2) {
                if (v1.live_sid == v2.live_sid) return NSOrderedSame;
                return v1.live_sid < v2.live_sid ? NSOrderedDescending : NSOrderedAscending;
            }];
        }
        [self.tableView reloadData];
    } failed:^(NSError *error) {
        @strongify(self);
//        [self.tableView endRefreshAndLoadMore];
    }];
}

- (void)updateLiveDataPaged: (NSInteger)p {
    [self updateLiveDataUrl:[NSString stringWithFormat:@"http://sportslive.firstblod.com/livetext/data/cache/livetext/%@/0/page_10/%ld.json?%d", self.model.id, p, rand()]];
}

- (void)updateLiveDataLit: (NSInteger)p {
    [self updateLiveDataUrl:[NSString stringWithFormat:@"http://sportslive.firstblod.com/livetext/data/cache/livetext/%@/0/lit_page_2/%ld.json?%d", self.model.id, p, rand()]];
}

- (void)checkLiveData {
    //if (_live_ver == 0) return; // init undone
    @weakify(self);
    [[MYHttpHelper shareHelper] getWithUrl:[NSString stringWithFormat:@"http://sportslive.firstblod.com/livetext/data/cache/livetext/%@/0/max_sid.json?%d", self.model.id, rand()] params:nil success:^(NSDictionary *dict) {
        @strongify(self);
        self.hintView.hintState = MYHintStateHidden;
//        self.failLb.hidden = YES;
//        self.tableView.hidden = NO;
        int v = [dict[@"max_sid"] intValue];
        if (self.live_ver == 0) {
            int last_page = v - v % 10;
            for (int i = last_page, j = 5; i > 0 && j > 0; i -= 10, j--) {
                [self updateLiveDataPaged:i];
            }
            for (int i = v + v % 2; i > last_page; i -= 2) {
                [self updateLiveDataLit:i];
            }
        }
        else if (v > self.live_ver) {
            for (int i = v + v % 2; i > self.live_ver; i -= 2) {
                [self updateLiveDataLit:i];
            }
        }
    } failed:^(NSError *error) {
        @strongify(self);
        [self.timer invalidate];
        self.timer = nil;
        self.hintView.hintState = MYHintStateNoData;
//        self.failLb.hidden = NO;
//        self.tableView.hidden = YES;
    }];
}

- (UIColor*)readColor: (NSString *)clr {
    if ([clr isKindOfClass:NSClassFromString(@"NSString")] && clr.length == 7 && [clr hasPrefix:@"#"]) {
        unsigned int r, g, b;
        [[NSScanner scannerWithString:[clr substringWithRange:NSMakeRange(1, 2)]] scanHexInt:&r];
        [[NSScanner scannerWithString:[clr substringWithRange:NSMakeRange(3, 2)]] scanHexInt:&g];
        [[NSScanner scannerWithString:[clr substringWithRange:NSMakeRange(5, 2)]] scanHexInt:&b];
        return [UIColor colorWithRed:((float)r) / 255 green:((float)g) / 255 blue:((float)b) / 255 alpha:1];
    }
    return [UIColor blackColor];
}

#pragma mark - uitableview

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.liveData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseId = @"heheheh";
    
    HSLiveDetailCell *cell=[tableView dequeueReusableCellWithIdentifier:reuseId];
    if (!cell) {
        cell = [[HSLiveDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseId];
    }
    cell.model = self.liveData[indexPath.row];
    [cell showLineForDirection:MYDirectionBottom];
    return cell;
}

#pragma mark - getter

- (UIView *)topView
{
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
        
        self.leftIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 50, 30) imageType:MYImageTypeSmallPic];
        self.leftIcon.centerX = ScreenWidth / 6;
        self.leftIcon.failureImageName = @"kedui";
        [self.leftIcon my_setImage:[NSString stringWithFormat:@"http://duihui.oss-cn-hangzhou.aliyuncs.com/zuqiu/%@.png", self.model.visit_logo]];
        [_topView addSubview:self.leftIcon];
        
        self.leftName = [UILabel labelWithFrame:CGRectMake(self.leftIcon.left, self.leftIcon.bottom + 5, ScreenWidth / 4, 40) font:MYFont(Font28) color:HEXCOLOR(HSColorBlack) text:self.model.visit_team.length ? self.model.visit_team : @"客队"];
        self.leftName.centerX = self.leftIcon.centerX;
        self.leftName.textAlignment = NSTextAlignmentCenter;
        self.leftName.numberOfLines = 0;
        [_topView addSubview:self.leftName];
        
        self.rightIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.leftIcon.top, self.leftIcon.width, self.leftIcon.height) imageType:MYImageTypeSmallPic];
        self.rightIcon.failureImageName = @"zhudui";
        self.rightIcon.centerX = ScreenWidth / 6 * 5;
        [self.rightIcon my_setImage:[NSString stringWithFormat:@"http://duihui.oss-cn-hangzhou.aliyuncs.com/zuqiu/%@.png", self.model.home_logo]];
        [_topView addSubview:self.rightIcon];
        
        self.rightName = [UILabel labelWithFrame:CGRectMake(self.rightIcon.left, self.rightIcon.bottom + 5, ScreenWidth / 4, self.leftName.height) font:MYFont(Font28) color:HEXCOLOR(HSColorBlack) text:self.model.home_team.length ? self.model.home_team : @"主队"];
        self.rightName.centerX = self.rightIcon.centerX;
        self.rightName.textAlignment = NSTextAlignmentCenter;
        self.rightName.numberOfLines = 0;
        [_topView addSubview:self.rightName];
        
        UILabel *tmp = [UILabel labelWithFrame:CGRectMake(0, 0, 10, self.leftIcon.height) font:MYFont(30) color:HEXCOLOR(HSColorBlack) text:@":"];
        tmp.centerX = ScreenWidth / 2;
        tmp.centerY = self.leftIcon.centerY;
        [_topView addSubview:tmp];
        
        self.leftScore = [UILabel labelWithFrame:CGRectMake(tmp.left - 5 - ScreenWidth / 6, 0, ScreenWidth / 6, 40) font:MYFont(30) color:HEXCOLOR(HSColorBlack) text:@"0"];
        self.leftScore.centerY = tmp.centerY;
        self.leftScore.textAlignment = NSTextAlignmentRight;
        [_topView addSubview:self.leftScore];
        
        self.rightScore = [UILabel labelWithFrame:CGRectMake(tmp.right + 5, 0, ScreenWidth / 6, 40) font:MYFont(30) color:HEXCOLOR(HSColorBlack) text:@"0"];
        self.rightScore.centerY = tmp.centerY;
        [_topView addSubview:self.rightScore];
        
        self.timeLb = [UILabel labelWithFrame:CGRectMake(0, self.leftScore.bottom + 10, ScreenWidth / 2, 15) font:MYFont(Font26) color:HEXCOLOR(HSColorGray) text:self.model.time];
        self.timeLb.centerX = tmp.centerX;
        self.timeLb.textAlignment = NSTextAlignmentCenter;
        [_topView addSubview:self.timeLb];
        [_topView showLineForDirection:MYDirectionBottom];
    }
    return _topView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.topView.bottom, self.view.width, self.view.height - self.topView.bottom - NavBarHeight)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}

- (UILabel *)failLb
{
    if (!_failLb) {
        _failLb = [UILabel labelWithFrame:self.tableView.frame font:MYFont(25) color:HEXCOLOR(HSColorBlack) text:@"小编正在来的路上........."];
        _failLb.backgroundColor = self.view.backgroundColor;
        _failLb.textAlignment = NSTextAlignmentCenter;
        _failLb.numberOfLines = 0;
        _failLb.hidden = YES;
    }
    return _failLb;
}

@end
